package com.exp04;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name="CheckUser",value = "/check")
public class CheckUserServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if(req.getSession().getAttribute("username")!=null){
            out.println("你好："+req.getSession().getAttribute("username")+"用户登录成功");
        }else{
            out.println("<body style=\"text-align:center;font-family:'FiraCode Nerd Font',serif\"> 还没有登录哦,5s后为您跳转至登录页</body>");
            resp.setHeader("refresh", "5;url=./");
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        System.out.println("SessionId=="+req.getSession().getId());
        String name = req.getParameter("username");
        //将用户的名称保存到session属性中
        req.getSession().setAttribute("username",req.getRemoteAddr()+name);
        //登录成功后，保存名称为JSESSIONID的id的cookie，值为session的id
        Cookie c = new Cookie("JSESSIONID",req.getSession().getId());
        c.setMaxAge(60*100);
        c.setPath("/");
        resp.addCookie(c);
        //调用doGet请求
        doGet(req,resp);
    }
}
